<template>
  <div class="color-picker">
    <el-card>
      <template #header>
        <div class="card-header">
          <h3>颜色选择器</h3>
        </div>
      </template>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-card class="color-input-card">
            <template #header>
              <div class="inner-card-header">
                <div class="title">选择颜色</div>
              </div>
            </template>

            <div class="color-preview" :style="{ backgroundColor: selectedColor }"></div>
            
            <el-form>
              <el-form-item>
                <el-color-picker
                  v-model="selectedColor"
                  show-alpha
                  @change="updateColorFormats"
                />
              </el-form-item>

              <el-form-item label="输入颜色值">
                <el-input
                  v-model="colorInput"
                  placeholder="输入HEX、RGB、HSL等格式的颜色值"
                  @input="parseColorInput"
                >
                  <template #append>
                    <el-button @click="parseColorInput">转换</el-button>
                  </template>
                </el-input>
              </el-form-item>
            </el-form>
          </el-card>
        </el-col>

        <el-col :span="12">
          <el-card class="color-output-card">
            <template #header>
              <div class="inner-card-header">
                <div class="title">颜色格式</div>
              </div>
            </template>

            <el-form>
              <el-form-item
                v-for="format in colorFormats"
                :key="format.label"
                :label="format.label"
              >
                <div class="color-format">
                  <el-input
                    v-model="format.value"
                    readonly
                  />
                  <el-button @click="copyFormat(format.value)">复制</el-button>
                </div>
              </el-form-item>
            </el-form>
          </el-card>
        </el-col>
      </el-row>

      <el-divider>调色板</el-divider>

      <div class="color-palette">
        <div class="palette-section">
          <h4>色调变化</h4>
          <div class="color-list">
            <div
              v-for="(color, index) in hueVariations"
              :key="'hue-' + index"
              class="color-item"
              :style="{ backgroundColor: color }"
              @click="selectPaletteColor(color)"
            >
              <span class="color-tooltip">{{ color }}</span>
            </div>
          </div>
        </div>

        <div class="palette-section">
          <h4>明度变化</h4>
          <div class="color-list">
            <div
              v-for="(color, index) in lightnessVariations"
              :key="'lightness-' + index"
              class="color-item"
              :style="{ backgroundColor: color }"
              @click="selectPaletteColor(color)"
            >
              <span class="color-tooltip">{{ color }}</span>
            </div>
          </div>
        </div>

        <div class="palette-section">
          <h4>饱和度变化</h4>
          <div class="color-list">
            <div
              v-for="(color, index) in saturationVariations"
              :key="'saturation-' + index"
              class="color-item"
              :style="{ backgroundColor: color }"
              @click="selectPaletteColor(color)"
            >
              <span class="color-tooltip">{{ color }}</span>
            </div>
          </div>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { ElMessage } from 'element-plus'

const selectedColor = ref('#409EFF')
const colorInput = ref('')

// 颜色格式列表
const colorFormats = ref([
  { label: 'HEX', value: '#409EFF' },
  { label: 'RGB', value: 'rgb(64, 158, 255)' },
  { label: 'RGBA', value: 'rgba(64, 158, 255, 1)' },
  { label: 'HSL', value: 'hsl(210, 100%, 62.5%)' },
  { label: 'HSLA', value: 'hsla(210, 100%, 62.5%, 1)' }
])

// 解析颜色字符串
const parseColor = (color) => {
  const div = document.createElement('div')
  div.style.color = color
  document.body.appendChild(div)
  const computedColor = getComputedStyle(div).color
  document.body.removeChild(div)
  return computedColor
}

// RGB转HEX
const rgbToHex = (r, g, b) => {
  const toHex = (n) => {
    const hex = n.toString(16)
    return hex.length === 1 ? '0' + hex : hex
  }
  return '#' + toHex(r) + toHex(g) + toHex(b)
}

// RGB转HSL
const rgbToHsl = (r, g, b) => {
  r /= 255
  g /= 255
  b /= 255

  const max = Math.max(r, g, b)
  const min = Math.min(r, g, b)
  let h, s, l = (max + min) / 2

  if (max === min) {
    h = s = 0
  } else {
    const d = max - min
    s = l > 0.5 ? d / (2 - max - min) : d / (max + min)

    switch (max) {
      case r: h = (g - b) / d + (g < b ? 6 : 0); break
      case g: h = (b - r) / d + 2; break
      case b: h = (r - g) / d + 4; break
    }

    h /= 6
  }

  return [
    Math.round(h * 360),
    Math.round(s * 100),
    Math.round(l * 100)
  ]
}

// 更新所有颜色格式
const updateColorFormats = () => {
  const div = document.createElement('div')
  div.style.backgroundColor = selectedColor.value
  document.body.appendChild(div)
  const computed = getComputedStyle(div).backgroundColor
  document.body.removeChild(div)

  const match = computed.match(/^rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*(\d+(?:\.\d+)?))?\)$/)
  if (match) {
    const [, r, g, b, a = '1'] = match
    const hex = rgbToHex(parseInt(r), parseInt(g), parseInt(b))
    const [h, s, l] = rgbToHsl(parseInt(r), parseInt(g), parseInt(b))

    colorFormats.value = [
      { label: 'HEX', value: hex },
      { label: 'RGB', value: `rgb(${r}, ${g}, ${b})` },
      { label: 'RGBA', value: `rgba(${r}, ${g}, ${b}, ${a})` },
      { label: 'HSL', value: `hsl(${h}, ${s}%, ${l}%)` },
      { label: 'HSLA', value: `hsla(${h}, ${s}%, ${l}%, ${a})` }
    ]
  }
}

// 解析输入的颜色值
const parseColorInput = () => {
  if (!colorInput.value) return

  try {
    const color = parseColor(colorInput.value)
    if (color) {
      selectedColor.value = color
      updateColorFormats()
    }
  } catch (e) {
    ElMessage.error('无效的颜色格式')
  }
}

// 复制颜色格式
const copyFormat = (text) => {
  navigator.clipboard.writeText(text)
    .then(() => ElMessage.success('复制成功'))
    .catch(() => ElMessage.error('复制失败'))
}

// 生成色调变化
const hueVariations = computed(() => {
  const variations = []
  for (let i = 0; i < 12; i++) {
    variations.push(`hsl(${i * 30}, 70%, 50%)`)
  }
  return variations
})

// 生成明度变化
const lightnessVariations = computed(() => {
  const variations = []
  for (let i = 0; i < 11; i++) {
    variations.push(`hsl(210, 70%, ${i * 10}%)`)
  }
  return variations
})

// 生成饱和度变化
const saturationVariations = computed(() => {
  const variations = []
  for (let i = 0; i < 11; i++) {
    variations.push(`hsl(210, ${i * 10}%, 50%)`)
  }
  return variations
})

// 选择调色板中的颜色
const selectPaletteColor = (color) => {
  selectedColor.value = color
  updateColorFormats()
}

// 初始化
updateColorFormats()
</script>

<style scoped>
.color-picker {
  max-width: 1200px;
  margin: 0 auto;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.inner-card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.title {
  font-size: 16px;
  font-weight: bold;
}

h3, h4 {
  margin: 0;
}

.color-preview {
  width: 100%;
  height: 100px;
  border-radius: 4px;
  margin-bottom: 20px;
  border: 1px solid #dcdfe6;
}

.color-format {
  display: flex;
  gap: 10px;
}

.color-palette {
  margin-top: 20px;
}

.palette-section {
  margin-bottom: 20px;
}

.palette-section:last-child {
  margin-bottom: 0;
}

.color-list {
  display: flex;
  gap: 10px;
  margin-top: 10px;
}

.color-item {
  width: 40px;
  height: 40px;
  border-radius: 4px;
  cursor: pointer;
  position: relative;
  border: 1px solid #dcdfe6;
}

.color-item:hover .color-tooltip {
  display: block;
}

.color-tooltip {
  display: none;
  position: absolute;
  bottom: 100%;
  left: 50%;
  transform: translateX(-50%);
  padding: 5px;
  background: rgba(0, 0, 0, 0.8);
  color: white;
  border-radius: 4px;
  font-size: 12px;
  white-space: nowrap;
  margin-bottom: 5px;
}

.color-tooltip::after {
  content: '';
  position: absolute;
  top: 100%;
  left: 50%;
  transform: translateX(-50%);
  border: 5px solid transparent;
  border-top-color: rgba(0, 0, 0, 0.8);
}
</style> 